package com.atguigu.gmall.realtime.dwd.db.split.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.base.BaseApp;
import com.atguigu.gmall.realtime.common.bean.TableProcessDwd;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.FlinkSinkUtil;
import com.atguigu.gmall.realtime.common.util.FlinkSourceUtil;
import com.atguigu.gmall.realtime.dwd.db.split.function.BaseDbTableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

public class DwdBaseDb extends BaseApp {
    public static void main(String[] args) {
        new DwdBaseDb().start(10019, 4, "dwd_base_db", Constant.TOPIC_DB);
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        // TODO 1.对流中数据进行类型转换以及ETL   jsonStr->jsonObj
        // {"database":"gmall0221","xid":925472,"data":{"order_status":"1006","create_time":"2024-07-23 19:13:03","id":19039,"order_id":9726},"commit":true,"type":"insert","table":"order_status_log","ts":1722424383}
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                        try {
                            JSONObject jsonObj = JSON.parseObject(jsonStr);
                            String type = jsonObj.getString("type");
                            if (!type.startsWith("bootstrap")){
                                collector.collect(jsonObj);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException("不是一个标准的json");
                        }
                    }
                }
        );
        //jsonObjDS.print();
        // TODO 2.通过Flink_CDC获取配置表信息
        MySqlSource<String> mysqlSource = FlinkSourceUtil.getMysqlSource("gmall0221_config", "table_process_dwd");
        DataStreamSource<String> mysqlStr = env.fromSource(mysqlSource, WatermarkStrategy.noWatermarks(), "mysql_source").setParallelism(1);
        //mysqlStr.print();
        // TODO 3.对流中数据进行类型转换 jsonStr -> 实体类对象
        //{"before":null,"after":{"source_table":"user_info","source_type":"insert","sink_table":"dwd_user_register","sink_columns":"id,create_time"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall0221_config","sequence":null,"table":"table_process_dwd","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1722425201137,"transaction":null}
        SingleOutputStreamOperator<TableProcessDwd> tpDS = mysqlStr.map(
                new MapFunction<String, TableProcessDwd>() {
                    @Override
                    public TableProcessDwd map(String jsonStr) throws Exception {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String op = jsonObj.getString("op");
                        TableProcessDwd tableProcessDwd = null;
                        if ("d".equals(op)) {
                            tableProcessDwd = jsonObj.getObject("before", TableProcessDwd.class);
                        } else {
                            tableProcessDwd = jsonObj.getObject("after", TableProcessDwd.class);
                        }
                        tableProcessDwd.setOp(op);
                        return tableProcessDwd;
                    }
                }
        );
        // TODO 4.对配置流进行广播
        MapStateDescriptor<String, TableProcessDwd> mapStateDescriptor = new MapStateDescriptor<String, TableProcessDwd>("mapStateDescriptor", String.class, TableProcessDwd.class);
        BroadcastStream<TableProcessDwd> broadcastDS = tpDS.broadcast(mapStateDescriptor);
        // TODO 5.主流和广播流进行合流
        BroadcastConnectedStream<JSONObject, TableProcessDwd> connectDS = jsonObjDS.connect(broadcastDS);
        // TODO 6.对关联后的数据进行处理process
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDwd>> realDS = connectDS.process(new BaseDbTableProcessFunction(mapStateDescriptor));
        // TODO 7.将过滤后的数据发送到kafka的不同的主题
        realDS.print();
        realDS.sinkTo(FlinkSinkUtil.getKafkaSink());
    }
}
